﻿using System;
using System.Web.Mvc;
using Popw.LiveBlog.Models;
using Popw.LiveBlog.Services;

namespace Popw.LiveBlog.Controllers
{
	[Authorize]
	public class AdminController : Controller
	{
		private readonly IContentService _contentService;
		private readonly IImageService _imageService;

		public AdminController(IContentService contentService, IImageService imageService)
		{
			_contentService = contentService;
			_imageService = imageService;
		}

		public ActionResult Index()
		{
			return View();
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Publish(string html, string name)
		{
			html = _contentService.ParseUrlsAndYouTube(html);
			var photo = Request.Files["photo"];
			if (photo != null && photo.ContentLength > 0)
			{
				var uri = _imageService.SaveImage(photo);
				var imageTag = String.Format("<img src=\"{0}\" />", uri);
				html = imageTag + html;
			}
			var contentItem = new ContentItem {Content = html, Name = name};
			_contentService.SaveContentItem(contentItem);
			return RedirectToAction("Index");
		}

		[HttpPost]
		public RedirectToRouteResult Delete(int id)
		{
			_contentService.Delete(id);
			return RedirectToAction("Index", "Home");
		}
	}
}